package leecode

func addToArrayForm(num []int, k int) []int {
	carry := 0 //进位
	arr := toArr(k)
	diff := abs989(len(arr) - len(num))
	temp := make([]int, diff)
	//补0
	if len(num) > len(arr) {
		arr = append(temp, arr...)
	} else {
		num = append(temp, num...)
	}
	result := make([]int, len(num)+1)
	for i := len(num) - 1; i >= 0; i-- {
		sum := num[i] + arr[i] + carry
		result[i+1] = sum % 10
		carry = sum / 10 //更新进位
	}
	if carry > 0 {
		result[0] = carry
	} else {
		result = result[1:]
	}
	return result
}

func toArr(num int) []int {
	var result []int
	for num > 0 {
		result = append(result, num%10)
		num = num / 10
	}
	reverse(result)
	return result
}

func reverse(arr []int) {
	i, j := 0, len(arr)-1
	for i < j {
		arr[i], arr[j] = arr[j], arr[i]
		i++
		j--
	}
}

func abs989(n int) int {
	if n < 0 {
		return -n
	}
	return n
}
